<template>
  <div class="dashboard-container">
    <panel-group :cards="summaryCards" :loading="loading" />

    <el-row :gutter="24" class="dashboard-row">
      <el-col :xs="24" :sm="12">
        <house-status-chart
          :data="houseStatusSeries"
          :loading="loading"
          :show-refresh="true"
          @refresh="loadDashboard"
        />
      </el-col>
      <el-col :xs="24" :sm="12">
        <tenant-status-chart
          :data="tenantStatusSeries"
          :loading="loading"
          :show-refresh="true"
          @refresh="loadDashboard"
        />
      </el-col>
    </el-row>

    <el-row :gutter="24" class="dashboard-row">
      <el-col :xs="24">
        <lease-status-chart
          :data="leaseStatusSeries"
          :loading="loading"
          :show-refresh="true"
          @refresh="loadDashboard"
        />
      </el-col>
    </el-row>
  </div>
</template>

<script>
import PanelGroup from "./dashboard/PanelGroup";
import HouseStatusChart from "./dashboard/HouseStatusChart";
import TenantStatusChart from "./dashboard/TenantStatusChart";
import LeaseStatusChart from "./dashboard/LeaseStatusChart";
import { listHouseRoom } from "@/api/house/houseRoom";
import { listTenant } from "@/api/system/tenant";
import { listHouseLease, fetchLeaseStatusOptions } from "@/api/house/lease";

const HOUSE_STATUS_META = [
  { key: "pending", code: 0, label: "待审核" },
  { key: "approved", code: 4, label: "已审核" },
  { key: "available", code: 1, label: "待出租" },
  { key: "leased", code: 2, label: "已出租" },
  { key: "closed", code: 3, label: "已下架" },
];

const TENANT_STATUS_META = [
  { key: "active", code: "0", label: "正常" },
  { key: "inactive", code: "1", label: "停用" },
];

export default {
  name: "Index",
  components: {
    PanelGroup,
    HouseStatusChart,
    TenantStatusChart,
    LeaseStatusChart,
  },
  data() {
    return {
      loading: false,
      summaryCards: [],
      houseStatusSeries: [],
      tenantStatusSeries: [],
      leaseStatusSeries: [],
    };
  },
  created() {
    this.loadDashboard();
  },
  methods: {
    async loadDashboard() {
      this.loading = true;
      try {
        const [houseStats, tenantStats, leaseStats] = await Promise.all([
          this.fetchHouseStats(),
          this.fetchTenantStats(),
          this.fetchLeaseStats(),
        ]);

        this.houseStatusSeries = houseStats.series;
        this.tenantStatusSeries = tenantStats.series;
        this.leaseStatusSeries = leaseStats.series;
        this.summaryCards = this.buildSummaryCards(houseStats, tenantStats, leaseStats);
      } catch (error) {
        // eslint-disable-next-line no-console
        console.error("Dashboard data load failed", error);
        this.$message.error("仪表盘数据加载失败，请稍后重试");
      } finally {
        this.loading = false;
      }
    },
    async fetchHouseStats() {
      const baseQuery = { pageNum: 1, pageSize: 1 };
      const totalPromise = listHouseRoom(baseQuery);
      const statusPromises = HOUSE_STATUS_META.map((meta) =>
        listHouseRoom({ ...baseQuery, state: meta.code })
      );
      const [totalRes, ...statusResults] = await Promise.all([totalPromise, ...statusPromises]);

      const total = totalRes?.total || 0;
      const statusMap = {};
      statusResults.forEach((result, index) => {
        const meta = HOUSE_STATUS_META[index];
        statusMap[meta.key] = result?.total || 0;
      });

      const series = HOUSE_STATUS_META.map((meta) => ({
        code: meta.code,
        label: meta.label,
        value: statusMap[meta.key] || 0,
      }));

      return {
        total,
        statuses: statusMap,
        series,
      };
    },
    async fetchTenantStats() {
      const baseQuery = { pageNum: 1, pageSize: 1 };
      const totalPromise = listTenant(baseQuery);
      const statusPromises = TENANT_STATUS_META.map((meta) =>
        listTenant({ ...baseQuery, status: meta.code })
      );
      const [totalRes, ...statusResults] = await Promise.all([totalPromise, ...statusPromises]);

      const total = totalRes?.total || 0;
      const statusMap = {};
      statusResults.forEach((result, index) => {
        const meta = TENANT_STATUS_META[index];
        statusMap[meta.key] = result?.total || 0;
      });

      const series = TENANT_STATUS_META.map((meta) => ({
        code: meta.code,
        label: meta.label,
        value: statusMap[meta.key] || 0,
      }));

      return {
        total,
        statuses: statusMap,
        series,
      };
    },
    async fetchLeaseStats() {
      const baseQuery = { pageNum: 1, pageSize: 1 };
      const [optionsRes, totalRes] = await Promise.all([
        fetchLeaseStatusOptions(),
        listHouseLease(baseQuery),
      ]);

      const options = optionsRes?.data?.items || [];
      if (!options.length) {
        return {
          total: totalRes?.total || 0,
          series: [],
          statuses: {},
        };
      }

      const statusPromises = options.map((option) =>
        listHouseLease({ ...baseQuery, status: option.code })
      );
      const statusResults = await Promise.all(statusPromises);

      const series = options.map((option, index) => ({
        code: option.code,
        label: option.label || option.name || option.code,
        value: statusResults[index]?.total || 0,
      }));

      const statusMap = series.reduce((acc, item) => {
        acc[item.code] = item.value;
        return acc;
      }, {});

      const total = totalRes?.total || series.reduce((sum, item) => sum + item.value, 0);

      return {
        total,
        series,
        statuses: statusMap,
      };
    },
    buildSummaryCards(houseStats, tenantStats, leaseStats) {
      const leasedCount = houseStats.statuses.leased || 0;
      const availableCount = houseStats.statuses.available || 0;
      const occupancyRate = this.calculateRate(leasedCount, houseStats.total);

      const topLeaseStatuses = [...leaseStats.series]
        .sort((a, b) => b.value - a.value)
        .slice(0, 2);

      return [
        {
          key: "houses",
          title: "房源总数",
          value: houseStats.total,
          unit: "套",
          color: "#409EFF",
          icon: "cu-house",
          breakdown: [
            { label: "待出租", value: availableCount, suffix: "套" },
            { label: "已出租", value: leasedCount, suffix: "套" },
            { label: "已下架", value: houseStats.statuses.closed || 0, suffix: "套" },
          ],
        },
        {
          key: "occupancy",
          title: "出租率",
          value: occupancyRate,
          decimals: 1,
          suffix: "%",
          color: "#E6A23C",
          icon: "chart",
          breakdown: [
            { label: "已出租", value: leasedCount, suffix: "套" },
            { label: "待出租", value: availableCount, suffix: "套" },
          ],
        },
        {
          key: "tenants",
          title: "租客总数",
          value: tenantStats.total,
          unit: "人",
          color: "#67C23A",
          icon: "peoples",
          breakdown: [
            { label: "正常", value: tenantStats.statuses.active || 0, suffix: "人" },
            { label: "停用", value: tenantStats.statuses.inactive || 0, suffix: "人" },
          ],
        },
        {
          key: "leases",
          title: "租约总数",
          value: leaseStats.total,
          unit: "份",
          color: "#F56C6C",
          icon: "documentation",
          breakdown: topLeaseStatuses.map((item) => ({
            label: item.label,
            value: item.value,
            suffix: "份",
          })),
        },
      ];
    },
    calculateRate(value, total) {
      if (!total || !value) return 0;
      return Number(((value / total) * 100).toFixed(1));
    },
  },
};
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 24px 24px 8px;
  background: #f5f7fa;

  .dashboard-row {
    margin-top: 24px;
  }
}

@media (max-width: 1024px) {
  .dashboard-container {
    padding: 16px;
  }
}
</style>
